package io.kiki.task.client.job.core.executor;

import cn.hutool.core.util.ServiceLoaderUtil;
import io.kiki.task.client.common.JobLogThreadLocal;
import io.kiki.task.client.common.ThreadLocal;
import io.kiki.task.client.common.threadlocal.CommonThreadLocal;
import io.kiki.task.common.core.model.JobContext;

import java.util.Objects;


public final class JobContextManager {
    private static final ThreadLocal<JobContext> JOB_CONTEXT_LOCAL = initThreadLocal();

    private JobContextManager() {
    }

    private static ThreadLocal<JobContext> initThreadLocal() {
        ThreadLocal<JobContext> threadLocal = ServiceLoaderUtil.loadFirst(JobLogThreadLocal.class);
        if (Objects.isNull(threadLocal)) {
            threadLocal = new CommonThreadLocal<>(new java.lang.ThreadLocal<>());
        }
        return threadLocal;
    }

    public static JobContext getJobContext() {
        return JOB_CONTEXT_LOCAL.get();
    }

    public static void setJobContext(JobContext jobContext) {
        JOB_CONTEXT_LOCAL.set(jobContext);
    }

    public static void removeJobContext() {
        JOB_CONTEXT_LOCAL.remove();
    }
}
